<template>
  <div class="addUser-mol" v-if="isLoad">
    <el-form
      label-width="260px"
      label-position="right"
      ref="userForm"
      :model="userForm"
      :rules="rules"
      @submit.native.prevent
    >
      <el-form-item label="成员姓名" prop="userName">
        <el-input
          v-model="userForm.userName"
          type="text"
          placeholder="请输入"
          :maxlength="maxLength"
          style="width:320px"
        ></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobilePhone">
        <el-input
          v-model="userForm.mobilePhone"
          type="text"
          placeholder="请输入"
          style="width:320px"
          :disabled="!userForm.id?false:true"
        ></el-input>
      </el-form-item>
      <el-form-item label="邮箱地址" prop="email">
        <el-input v-model="userForm.email" type="text" placeholder="请输入" style="width:320px"></el-input>
      </el-form-item>
      <el-form-item label="登录密码" prop="loginPwd" v-if="!userForm.id">
        <el-input v-model="userForm.loginPwd" type="password" placeholder="请输入" style="width:320px"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="loginPwds" v-if="!userForm.id">
        <el-input
          v-model="userForm.loginPwds"
          type="password"
          placeholder="请输入"
          style="width:320px"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户身份" prop="userType" v-if="projectId === 3">
        <el-select v-model="userForm.userType" placeholder="请选择" style="width:320px">
          <!-- :disabled="!userForm.id?false:true" -->
          <el-option
            v-for="item in userTypeList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="养殖企业"
        prop="enterpriseId"
        v-if="userForm.userType === 1 && projectId === 3"
      >
        <el-select v-model="userForm.enterpriseId" filterable clearable style="width:320px">
          <el-option
            v-for="item in enterpriseOptions"
            :key="item.enterpriseId"
            :label="item.name"
            :value="`${item.enterpriseId}`"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="角色权限" prop="orgId">
        <template v-if="superAdmin">
          <div v-for="(items, index) in proRoleOptions" :key="index" style="margin-bottom:10px">
            <el-checkbox v-model="items.checked" @change="initIpt">{{items.name}}</el-checkbox>
            <el-select
              v-model="items.roles"
              @change="handleOrg"
              placeholder="请选择"
              style="margin-left:10px;width:147px"
            >
              <el-option
                v-for="item in items.roleList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </div>
        </template>
        <template v-else>
          <el-select v-model="userForm.orgId" placeholder="请选择">
            <el-option
              v-for="item in roleLists"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </template>
      </el-form-item>
      <el-form-item
        label="养殖企业"
        prop="compList"
        v-if="showEnterprise"
      >
        <el-select v-model="userForm.compList" filterable multiple clearable style="width:320px">
          <el-option label="全部" :value="1" />
          <el-option
            v-for="item in enterpriseOptions" :key="item.enterpriseId"
            :label="item.name" :value="item.enterpriseId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属部门" prop="govDepId" v-if="showGovDepSelecter">
        <el-select v-model="userForm.govDepId" placeholder="请选择" style="width:320px">
          <el-option
            v-for="item in govDepOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="addbtn">
      <el-button type="primary" @click="submitDialog('userForm')">提交</el-button>
    </div>
  </div>
</template>

<script>
import { publicKey, getSession } from '@/utils/index'
import { REG, TEXT_MESSAGE } from '@/utils/verification'
import { JSEncrypt } from 'jsencrypt'
export default {
  name: 'userManageAdd',
  data () {
    let checkphone = (rule, value, callback) => {
      let phoneReg = /^1\d{10}$/;
      if (value === '') {
        callback(new Error('请输入手机号码'));
      } else if (!phoneReg.test(value)) {
        callback(new Error('请输入正确的手机号'));
      } else {
        callback();
      }
    }
    let checkConfirmPwd = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入登录密码!'))
      } else if (value !== this.userForm.loginPwd) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    let projectId = this.$store.state.user.projectId;
    return {
      isLoad: false,
      maxLength: 6,
      roleLists: [],
      userForm: {
        projectId: projectId,
        id: null,
        userName: '',
        mobilePhone: '',
        email: '',
        orgId: '',
        loginPwd: '',
        loginPwds: '',
        userType: null,
        enterpriseId: ''
      },
      projectId: Number(projectId),
      rules: {
        userName: [
          { required: true, message: '请输入成员名称', trigger: 'blur' },
          { pattern: /^[\u4e00-\u9fa5]{2,6}$/, message: '只能输入中文,且最少输入2个，最多输入6个', trigger: 'blur' }
        ],
        mobilePhone: { required: true, validator: checkphone, trigger: 'blur' },
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { pattern: REG.email, message: TEXT_MESSAGE.email, trigger: 'blur' }
        ],
        orgId: { required: true, message: '请选择角色权限', trigger: 'change' },
        loginPwd: [
          { required: true, message: '登录密码不能为空', trigger: 'blur' },
          { pattern: REG.passWord, message: TEXT_MESSAGE.passWord, trigger: 'blur' }
        ],
        loginPwds: { required: true, validator: checkConfirmPwd, trigger: 'blur' },
        userType: { required: true, message: '请选择用户身份', trigger: 'change' },
        enterpriseId: { required: true, message: '请选择养殖企业', trigger: 'change' },
        compList: { required: false, message: '请选择养殖企业', trigger: 'blur' },
      },
      superAdmin: this.$store.state.user.isSuperAdmin === 'true',
      proRoleOptions: [],
      singleOrgIds: {},
      userTypeList: [
        { id: 0, name: '普通用户' },
        { id: 1, name: '养殖户' },
        { id: 2, name: '政府人员' },
        { id: 3, name: '金融机构' },
        { id: 4, name: '管理员' }
      ],
      enterpriseOptions: [],
      showEnterprise: false,
      govDepOptions: [],
      showGovDepSelecter: false,
    };
  },
  watch: {
    'userForm.userName' (val) {
      let leng = this.validateTextLength(val)
      this.maxLength = leng >= 6 ? 6 : 12
    }
  },
  async mounted () {
    await this.getListEnterpriseData();
    await this.getGovDepList();
    this.isLoad = true;
    if (this.superAdmin) {
      this.proRoleOptions = await this.getProRoleOptions();
    } else {
      this.getRoleList();
    }
    this.userForm.id = this.$route.query.id ? this.$route.query.id : null
    if (this.userForm.id) this.getUserDetail();
  },
  methods: {
    initIpt () {
      this.$forceUpdate();
    },
    /* 获取全部的角色及项目信息 */
    getProRoleOptions () {
      return new Promise((resolve, reject) => {
        this.$api.business.findAllRoleList({}).then(res => {
          resolve(res.data || []);
        }).catch(res => {
          reject(res);
        });
      });
    },
    /* 获取角色列表 */
    getRoleList () {
      this.$api.role.getRoleList({
        projectId: this.projectId,
      }).then(res => {
        this.roleLists = res.data
      });
    },
    /* 获取成员详情 */
    getUserDetail () {
      this.$api.member.getUserDetail({
        id: this.userForm.id,
        mobilePhone: this.$route.query.mobilePhone || '',
        projectId: this.$route.query.projectId || this.projectId
      }).then(async res => {
        let orgIds = JSON.parse(res.data.orgId)
        this.userForm = res.data
        this.userForm.enterpriseId = this.userForm.enterpriseId === '0' ? '' : this.userForm.enterpriseId;
        this.userForm.loginPwds = res.data.loginPwd;
        this.userForm.compList = this.userForm.compList ? this.userForm.compList.split(',').filter( o => o).map((item) => item && Number(item)) : '';
        this.showEnterprise = await this.getAllMenuAuth(orgIds[this.projectId])
        if (this.superAdmin) {
          this.proRoleOptions.map(o => {
            for (let key in orgIds) {
              if (Number(key) === o.id) {
                o.checked = true
                o.roles = orgIds[key]
              }
            }
          })
        } else {
          this.userForm.orgId = orgIds[this.projectId];
          this.singleOrgIds = orgIds;
        }
        console.log(this.userForm, this.userForm.orgId,this.userForm.orgId[1]);
        const orgId = JSON.parse(this.userForm.orgId) && JSON.parse(this.userForm.orgId)[1]
        if (orgId === 28) this.showGovDepSelecter = true
        this.$forceUpdate()
      });
    },
    formatArr (data) {
      let newdata = [];
      if (!data) {
        newdata = [];
      } else if (data.indexOf(',') !== -1) {
        newdata = data.split(',');
      } else {
        newdata = [data];
      }
      return newdata;
    },
    resetFrom () {
      this.userForm = {
        projectId: this.projectId,
        id: null,
        userName: '',
        mobilePhone: '',
        email: '',
        orgId: '',
        loginPwd: '',
        loginPwds: '',
        userType: null,
        enterpriseId: ''
      }
      this.$refs['userForm'].resetFields()
    },
    submitDialog (formName) {
      let noRole = false;
      let projectIds = [];
      let proroles = {};
      if (this.superAdmin) {
        this.proRoleOptions.map(o => {
          if (o.checked) {
            projectIds.push(o.id);
            o.roles ? proroles[o.id] = o.roles : noRole = true;
          }
        })
        this.userForm.orgId = JSON.stringify(proroles) !== '{}' ? proroles : ''
      } else {
        proroles = this.singleOrgIds;
        proroles[this.projectId] = this.userForm.orgId;
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // this.userForm.loginPwd =
          const key = publicKey()
          const encryptor = new JSEncrypt()
          encryptor.setPublicKey(key)
          const newencrypted = encryptor.encrypt(this.userForm.loginPwd)
          this.userForm.loginPwd = newencrypted
          this.userForm.loginPwds = newencrypted
          let { id, userName, loginPwd, mobilePhone, email, orgId, projectId, userType, enterpriseId, compList, govDepId } = this.userForm
          if (this.superAdmin) {
            if (noRole) {
              this.$message.warning('请选择角色');
              return;
            }
            if (!projectIds.length) {
              this.$message.error('请选择角色权限');
              return;
            }
          }
          if (this.superAdmin) projectId = projectIds.join(',')
          // if (!this.superAdmin) proroles[projectId] = orgId
          orgId = JSON.stringify(proroles)
          let addParms = {
            id,
            projectId,
            userName,
            loginPwd,
            mobilePhone,
            email,
            orgId,
            userType,
            govDepId,
            enterpriseId: userType === 1 ? enterpriseId : '',
            compList: this.showEnterprise ? compList.join() : '',
          }
          let editParms = {
            id,
            projectId,
            userName,
            // loginPwd,
            mobilePhone,
            email,
            orgId,
            userType,
            govDepId,
            enterpriseId: userType === 1 ? enterpriseId : '',
            compList: this.showEnterprise ? compList.join() : '',
          }
          if (!this.showGovDepSelecter) {
            addParms.govDepId = ''
            editParms.govDepId = ''
          }
          if (!addParms.enterpriseId || !editParms.enterpriseId) {
            delete addParms.enterpriseId
            delete editParms.enterpriseId
          }
          // return false
          // {
          //   id,
          //   projectId,
          //   userName,
          //   // loginPwd,
          //   mobilePhone,
          //   email,
          //   orgId,
          //   userType,
          //   enterpriseId: userType === 1 ? enterpriseId : ''
          // }
          this.$api.member.editOrAddUser(this.userForm.id ? editParms : addParms).then(() => {
            this.$message({
              message: '保存成功',
              type: 'success'
            })
            setTimeout(() => {
              this.$router.push({ path: 'index' })
              !this.userForm.id && this.resetFrom()
            }, 500)
          });
        } else {
          return false
        }
      })
    },
    //校验字符长度
    validateTextLength (value) {
      // 中文、中文标点、全角字符按1长度，英文、英文符号、数字按0.5长度计算
      let cnReg = /([\u4e00-\u9fa5]|[\u3000-\u303F]|[\uFF00-\uFF60])/g
      let mat = value.match(cnReg)
      let length = 0
      if (mat) {
        length = (mat.length + (value.length - mat.length) * 0.5)
        return length
      } else {
        return value.length * 0.5
      }
    },
    getListEnterpriseData () {
      return new Promise((resolve, reject) => {
        var param = {
          projectId: this.projectId,
          currentPage: 1,
          pageSize: 1000,
          source: 0
        }
        if (this.projectId === 2) {
          param.enterpriseType = 0
        }
        this.$api.data.getListEnterpriseInfo(param).then(res => {
          this.enterpriseOptions = res.data || [];
          resolve()
        }).catch(res => {
          reject();
        });
      });
    },
    async getListEnterpriseData () {
      const { data } = await this.$api.retrace.getEnterpriseSelectList({enterpriseType: 1})
      this.enterpriseOptions = data
    },
    async handleOrg (orgId) {
      this.$forceUpdate();
      this.showEnterprise = await this.getAllMenuAuth(orgId)
      orgId === 28? this.showGovDepSelecter = true : this.showGovDepSelecter = false
    },
    async getAllMenuAuth (orgId) {
      const { data } = await this.$api.role.getAllMenu({
        orgId,
        projectId: this.$store.state.user.projectId,
        isSuperAdmin: this.superAdmin
      })
      const checked1 = data[0].children.find( o => o.menuName === '生产数字化系统').checked
      const checked2 = data[2].children.find( o => o.menuName === '生产数字化系统').checked
      if(checked1 || checked2) {
        this.rules.compList.required = true
        this.$forceUpdate()
      }
      return checked1 || checked2
    },
    async getGovDepList() {
      const { data } = await this.$api.member.getGovDepList({enterpriseType: 1})
      this.govDepOptions = data
    }
  }
};
</script>
